package com.demo.instance;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * FileName: WaterRobot.java
 * 灌水机器人，每隔2秒灌水一次，直到灌满为止
 *
 * @author Pretty_Boy
 * @version 1.00
 * @Date 2018/9/2914:54
 */
public class WaterRobot extends TimerTask {
    private Integer bucket = 0;
    private Timer timer;

    public WaterRobot(Timer timer) {
        this.timer = timer;
    }

    @Override
    public void run() {
        if (bucket < 5) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateNow = dateFormat.format(System.currentTimeMillis());

            System.out.println("Watering----" + dateNow);
            bucket++;
        }else {
            System.out.println("已经取消的任务----》》》" + timer.purge());
            cancel();
            System.out.println("当前桶里水的容量是" + bucket + "升");
            System.out.println("已经取消的任务----》》》" + timer.purge());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //取消所有任务
            timer.cancel();
        }

    }
}
